package org.zjx.db;


import org.zjx.enums.prop.SlotType;
import org.zjx.model.prop.ItemSlot;

import java.util.List;

public class ItemSlotDB {
    private static boolean isTableCreated = false;
    private final SQLiteHelper dbHelper;

    public ItemSlotDB() {
        dbHelper = SQLiteHelper.getSingleton();
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS item_slots (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    slotType TEXT NOT NULL,\n"
                + "    position INTEGER NOT NULL,\n"
                + "    status TEXT DEFAULT 'NORMAL'\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    public void insert(ItemSlot slot) {
        String sql = "INSERT INTO item_slots(slotType, position, status) VALUES(?, ?, ?)";
        Object[] params = {
                slot.getSlotType().name(),
                slot.getPosition(),
                slot.getStatus().name()
        };
        // 获取生成的自增ID并设置回实例对象
        long generatedId = dbHelper.executeUpdate(sql, params);
        if (generatedId != -1) {
            slot.setId((int) generatedId);
        }

    }

    public void update(ItemSlot slot) {
        String sql = "UPDATE item_slots SET slotType = ?, position = ?, status = ? WHERE id = ?";
        Object[] params = {
                slot.getSlotType().name(),
                slot.getPosition(),
                slot.getStatus().name(),
                slot.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    public void deleteById(int id) {
        String sql = "DELETE FROM item_slots WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    public ItemSlot findById(int id) {
        String sql = "SELECT * FROM item_slots WHERE id = ?";
        Object[] params = {id};
        List<ItemSlot> slots = dbHelper.executeQuery(sql, params, ItemSlot.class);
        return slots.isEmpty() ? null : slots.get(0);
    }

    public List<ItemSlot> findByType(SlotType slotType) {
        String sql = "SELECT * FROM item_slots WHERE slotType = ? ORDER BY position";
        Object[] params = {slotType.name()};
        return dbHelper.executeQuery(sql, params, ItemSlot.class);
    }

    public List<ItemSlot> findAll() {
        String sql = "SELECT * FROM item_slots";
        return dbHelper.executeQuery(sql, null, ItemSlot.class);
    }

    public void clearData() {
        dbHelper.clearData("item_slots");
    }

    public void dropTable() {
        dbHelper.dropTable("item_slots");
    }
}